/* eslint-disable array-callback-return */
/* eslint-disable no-empty-pattern */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
/* eslint-disable no-restricted-globals */
/* global window */

import { history } from 'umi'
import { stringify } from 'qs'
const { pathToRegexp } = require('path-to-regexp')

const goDashboard = (route) => {
  if (pathToRegexp(['/', '/login']).exec(window.location.pathname)) {
    history.push({
      pathname: route[0],
    })
  }
}
const isPC = () => {
  /*true则pc，false则mobile*/
  let u = navigator.userAgent
  let Agents = [
    'Android',
    'iPhone',
    'webOS',
    'BlackBerry',
    'SymbianOS',
    'Windows Phone',
    'iPad',
    'iPod',
  ]
  let flag = true
  for (let i = 0; i < Agents.length; i++) {
    if (u.indexOf(Agents[i]) > 0) {
      flag = false
      break
    }
  }
  return flag
}
export default {
  namespace: 'app',
  state: {
    routeList: [],
    locationPathname: '',
    locationQuery: {},
    theme: sessionStorage.getItem('theme') || 'dark',
    collapsed: Boolean(sessionStorage.getItem('collapsed')) || false,
    notifications: [
      {
        title: 'New User is registered.',
        date: new Date(Date.now() - 10000000),
      },
      {
        title: 'Application has been approved.',
        date: new Date(Date.now() - 50000000),
      },
    ],
  },
  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },
    setupHistory({ dispatch, history }) {
      history.listen((location) => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        })
      })
    },

    setupRequestCancel({ history }) {
      history.listen(() => {
        const { cancelRequest = new Map() } = window
        cancelRequest.forEach((value, key) => {
          if (value.pathname !== window.location.pathname) {
            value.cancel(CANCEL_REQUEST_MESSAGE)
            cancelRequest.delete(key)
          }
        })
      })
    },
  },
  effects: {
    // eslint-disable-next-line require-yield
    *query({}, { call, put, select }) {
      // store isInit to prevent query trigger by refresh
      const isInit = sessionStorage.getItem('isInit')
      sessionStorage.removeItem('openKeys')
      if (isInit) {
        goDashboard()
        return
      }
      const Theuser = JSON.parse(sessionStorage.getItem('Theuser'))
      let success = false
      if (Theuser) {
        success = true
      }
      let user = { 
        id: 0,
        username: 'admin',
        permissions: {
          role: 'admin',
        },
        avatar:
          '//image.zuiidea.com/photo-1534308143481-c55f00be8bd7.jpeg?imageView2/1/w/200/h/200/format/webp/q/75|imageslim',
      }
      if (success && user) {
        let list = [
          {
            id: '1',
            icon: 'dashboard',
            name: 'Myclassroom',
            zh: { name: '我的课堂' },
            ja: { name: '我的课堂' },
            route: '/Myclassroom',
          },
          {
            id: '2',
            icon: 'dashboard',
            name: 'ClassroomTest',
            zh: { name: '课堂检测' },
            ja: { name: '课堂检测' },
            route: '/ClassroomTest',
          },
          {
            id: '2-1',
            menuParentId: '-1',
            breadcrumbParentId: '2',
            icon: 'dashboard',
            name: 'ClassroomTest',
            zh: { name: '课堂检测' },
            ja: { name: '课堂检测' },
            route: '/ClassroomTest/:id',
          },
          {
            id: '3',
            icon: 'dashboard',
            name: 'Myhomework',
            zh: { name: '我的作业' },
            ja: { name: '我的作业' },
            route: '/Myhomework',
          },
          {
            id: '4',
            icon: 'dashboard',
            name: 'Myworks',
            zh: { name: '我的作品' },
            ja: { name: '我的作品' },
            route: '/Myworks',
          },
          {
            id: '5',
            icon: 'dashboard',
            name: 'DisplayWorks',
            zh: { name: '展示作品' },
            ja: { name: '展示作品' },
            route: '/DisplayWorks',
          },
          // {
          //     id: '6',
          //     icon: 'dashboard',
          //     name: 'ProgrammingTool',
          //     zh: { name: '编程工具'},
          //     ja: { name: '编程工具' },
          //     route: '/ProgrammingTool',
          // },
          {
            id: '7',
            icon: 'dashboard',
            name: 'ClassResources',
            zh: { name: '班级资源' },
            ja: { name: '班级资源' },
            route: '/ClassResources',
          },

          {
            id: '6',
            menuParentId: '6',
            breadcrumbParentId: '6',
            name: 'programming',
            icon: 'ToolOut-icon',
            zh: { name: '编程工具' },
            ja: { name: 'アカウント管理です' },
            route: '/programming',
          },
          {
            id: '6-1',
            menuParentId: '-1',
            breadcrumbParentId: '6',
            name: 'programming',
            zh: { name: '编程工具' },
            ja: { name: 'アカウント管理です' },
            route: '/programming/:id',
          },
        ]
        let listdata = JSON.parse(sessionStorage.getItem('Permission'))
        let dataIten = []
        let dataItem = []
        list.map((item, index) => {
          // || item.id.length > 6
          if (listdata.includes(item.id)) {
            dataIten.push(item)
            dataItem.push(item.id)
          }
        })
        let permissions = {
          visit: '',
        }
        permissions.visit = dataItem
        sessionStorage.setItem('routeList', JSON.stringify(dataIten))
        sessionStorage.setItem('permissions', JSON.stringify(permissions))
        sessionStorage.setItem('user', JSON.stringify(user))
        sessionStorage.setItem('isInit', true)
        let router = []
        dataIten.map((item, index) => {
          if (item.route) {
            router.push(item.route)
            return
          }
        })
        goDashboard(router)
      } else {
        history.push({
          pathname: '/login',
          search: stringify({
            from: {},
          }),
        })
      }
    },

    *signOut({ payload }, { call, put }) {
      sessionStorage.removeItem('Theuser')
      sessionStorage.removeItem('routeList')
      sessionStorage.removeItem('permissions')
      sessionStorage.removeItem('user')
      sessionStorage.removeItem('isInit')
      sessionStorage.removeItem('openKeys')
      sessionStorage.removeItem('Permission')
      sessionStorage.removeItem('timeout')
      // location.reload()
      yield put({ type: 'query' })
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },

    handleThemeChange(state, { payload }) {
      sessionStorage.setItem('theme', payload)
      state.theme = payload
    },

    handleCollapseChange(state, { payload }) {
      sessionStorage.setItem('collapsed', payload)
      state.collapsed = payload
      return {
        ...state,
        ...payload,
      }
    },

    allNotificationsRead(state) {
      state.notifications = []
    },
  },
}
